from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait  # 等待页面加载某些元素
# from selenium.webdriver import ActionChains
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions as EC
import time
import xlwt,xlrd
import os


option = Options()
# 忽略警告语
option.add_experimental_option('excludeSwitches', ['enable-automation'])
driver = webdriver.Chrome(options=option, executable_path="chromedriver.exe")
# driver = webdriver.Edge()
driver.get("https://i.cnblogs.com/posts")
# driver.get("https://passport.csdn.net/newlogin?code=mobile")
wait = WebDriverWait(driver, 10)  # 等待元素加载，最多7s

# 调整窗口大小
window_size = driver.get_window_size()
driver.set_window_size(1200, window_size['height'])
time.sleep(60)#等待这段时间手动输入用户名、密码验证码登录系统

def get_coo():
    time.sleep(40)#等待这段时间手动输入用户名、密码验证码登录系统
    cookies=driver.get_cookies()#获取登录过程中的cookie信息
    print(cookies)
    """
    {'domain': '.cnblogs.com', 'expiry': 1637925382, 'httpOnly': False, 'name': '_gid', 'path': '/', 'secure': False, 'value': 'GA1.2.155328472.1637838983'}, 
    {'domain': '.cnblogs.com', 'expiry': 1700910982, 'httpOnly': False, 'name': '_ga', 'path': '/', 'secure': False, 'value': 'GA1.2.180429942.1637838964'},
    {'domain': '.cnblogs.com', 'expiry': 1637839042, 'httpOnly': False, 'name': '_gat_gtag_UA_48445196_1', 'path': '/', 'secure': False, 'value': '1'}, 
    {'domain': '.cnblogs.com', 'expiry': 1700910982, 'httpOnly': False, 'name': '_ga_3Q0DVSGN10', 'path': '/', 'secure': False, 'value': 'GS1.1.1637838964.1.1.1637838982.0'},
    {'domain': '.cnblogs.com', 'expiry': 1639134982, 'httpOnly': True, 'name': '.CNBlogsCookie', 'path': '/', 'secure': False, 'value': '4F2B854D3CA0DA04723D05821621243C804239762BD7E7B7A9443B42EF6475CC0A21A091769CBC3D55E3972CB83A2FA449130D17073D028E5E289B9750C199365934EF1951B74A545881816F4041E6417C3069F6'} 
    {'domain': 'i.cnblogs.com', 'httpOnly': False, 'name': 'XSRF-TOKEN', 'path': '/', 'secure': True, 'value': 'CfDJ8FO3GXnjClZGrNGr2Ic8Z1qFQrp0fr6BQGIORoxoJ4XZv7qi50T7x3exsIFeVjrKX35VMIowDslLRHOBAOMONsXNVzgO-7CBG9C7h4-0WRUyjbJiB593kimgQZ6fInPvkqKz2H2NlM12ihAyiDmqHOgEDKU4MetlDegRV0b8N2Gq9OoAqc4qk4zLkKkrzF3BUg'}, 
    {'domain': '.cnblogs.com', 'expiry': 1639134982, 'httpOnly': True, 'name': '.Cnblogs.AspNetCore.Cookies', 'path': '/', 'secure': False, 'value': 'CfDJ8FO3GXnjClZGrNGr2Ic8Z1p4LoWPIoHwvf00nlqXytZDP06QuV8LNBaZvTkz20XI5_xzqrmyfJZki3k7wcPgeojbuqABX9ak502ivxvAWz_oJr3zC_M2cdlau5fHBNlte3C9m7ISo0Gxl_oCRTdcda4adO-W3sX7hAXKMc-_4vJW5DCYFZZ-KuHpruxjphHs7zN1ZDEdnKlzmEcVDKuOp0cP2ERQ450yDdWh7BO0k8IG03v1o1JeSDOUQzxoOPXOlBV7DNqQNHMpNzfDF3vkpbul9J8-hcMPGv6OHoTR-DRJhDcudiWnEd7Il_5FWcd7Cu2siT-hcL-rY_VMktQi-nHScbv35LhzaZYZ5GOy-S911sGeaBgHH5_c5lV2fsoycYR4sshEzP4_w7CvphgKcCMkqcyHBGOno-YJkpR_kF0J15p9y9e2G_7d3G3F9oXaABSZQszBhsdM4lBiw0Ae_NuWb781yeamlY3VUDIr1uljKRVOgxMUBeztG-ACtZ0igBZnwkGEPlvBh0epj8KMBbOZswmgvRocImBMdA_d_AEzY1MzahKNmpjF58ziTX-G1U16ozMdIPNhzhAoNn2_TD8'}, 
    {'domain': 'i.cnblogs.com', 'httpOnly': True, 'name': '.AspNetCore.Antiforgery.b8-pDmTq1XM', 'path': '/', 'secure': False, 'value': 'CfDJ8FO3GXnjClZGrNGr2Ic8Z1qP4f6xrlNY7aR1Tb-Xs1d9Mzr5NehR9xLhOPlw5cJYb7ibImZDoIZ1ZKbk4jzKUuA5TRywHvFWrWbnjMcaXJeaG3cjgwqFsaqXptk4qyQvxxx9ujwCSSTZc_a5nVqZmUM'}]
    """
    cookies = [{'domain': '.cnblogs.com', 'expiry': 1637926096, 'httpOnly': False, 'name': '_gid', 'path': '/', 'secure': False, 'value': 'GA1.2.888306002.1637839696'}, {'domain': '.cnblogs.com', 'expiry': 1700911696, 'httpOnly': False, 'name': '_ga', 'path': '/', 'secure': False, 'value': 'GA1.2.1241753544.1637839674'}, {'domain': '.cnblogs.com', 'expiry': 1637839756, 'httpOnly': False, 'name': '_gat_gtag_UA_48445196_1', 'path': '/', 'secure': False, 'value': '1'}, {'domain': '.cnblogs.com', 'expiry': 1700911696, 'httpOnly': False, 'name': '_ga_3Q0DVSGN10', 'path': '/', 'secure': False, 'value': 'GS1.1.1637839674.1.1.1637839695.0'}, {'domain': '.cnblogs.com', 'httpOnly': True, 'name': '.CNBlogsCookie', 'path': '/', 'secure': False, 'value': '9FB594BE3D7A5158E49120CC1C8879D343398BD050185BABACD36CFAA49B67DB53FD861287DE345613E9ECC6E894AED408E46496E4EA5A2FF0CAC7F02C7024006D1D479E9391CEA5D994D245829FA0A611D5FBA2'}, {'domain': 'i.cnblogs.com', 'httpOnly': False, 'name': 'XSRF-TOKEN', 'path': '/', 'secure': True, 'value': 'CfDJ8FO3GXnjClZGrNGr2Ic8Z1rcuYHlpTrCAUTHEuNCNi3UBfWrv4XLgyNLB2H2KuR3wuM938_ZnXNeNRP_jU4_OEdDd546erRAic22Nt3He3b9TBBVx1sI-xkxMyVHEP-7hpJc28hKRQL1OEijEQH4754XjOu9JMhGvg-WFq_8VnqJ5QZRRJzKH6aLwTQumekQ_A'}, {'domain': '.cnblogs.com', 'httpOnly': True, 'name': '.Cnblogs.AspNetCore.Cookies', 'path': '/', 'secure': False, 'value': 'CfDJ8FO3GXnjClZGrNGr2Ic8Z1oUXl7UbF4UAo25gSgoNFhZTxYhX42mmuUX8ylOVnO4PYp8oqHzfiLwVKGj58PkRQ5c6visNw2lzBvpllWBpJpbZLBksZV0RNJmw46Qw1sRsgQKJ8vL7F7fdJjtOyYhh9I6JgKB1Z_fRyc_3ohc_QC0FYzx9xl70jOyKLtVCEov6nQc1Ip7ptfie2dAJfA1ZOlTTJoOxv7PWsECrK2wQHAvSkY9CXU_ci8OidEIzCxsXt5rN0EZljRcFeZSRtNxwCwKOD6ObLYt6c-4f3BLJ2v6CCE4PVUR7Kv6VI99e6TauazGMHz6jf17UCpzHLFINwLROUI-fcXHr-6OKNtR7r4PQlUCUkXRuKm7CZH0Vf7IZRHT50WCLupMtDaG3M-qSYCvycq2SofeBZAzLtNISOpiM_zEpVxBteW3xADtObClmk4kL0FmfiK96CF8fyq-sqlBa0QeJFIzoHslTotyZ-plLqaIbAeIdc9yyL2CHUfrhEvljQ6v6riVIRxfvYch-3wi_AsQK31YtFDNj_wDbaJJYhrv__GoE7cE8iCs5O9Wcg'}, {'domain': 'i.cnblogs.com', 'httpOnly': True, 'name': '.AspNetCore.Antiforgery.b8-pDmTq1XM', 'path': '/', 'secure': False, 'value': 'CfDJ8FO3GXnjClZGrNGr2Ic8Z1pWwWWaRao2juxo6gcnw126uKs_ix_g1JbSHeXSPT-K0f_yna71Xi5xH3hW2sVy2Enpk7twtHOxUkSgeyyhJQG6qERjPCxeunTHRb87QoWclGLCk0FB5Kewqo6oJEqISQ4'}]

    #shx15979391664@163.com
    # 把cookies的key写入excel文件中第一行
    workbook=xlwt.Workbook(encoding='utf-8')
    worksheet=workbook.add_sheet('Sheet1')
    worksheet.write(0,0,'domain')
    worksheet.write(0,1,'httpOnly')
    worksheet.write(0,2,'name')
    worksheet.write(0,3,'path')
    worksheet.write(0,4,'secure')
    worksheet.write(0,5,'value')
    # 使用for循环把cookie的value值写入接下来的每一行中
    for row_num in range(1,len(cookies)+1):#第0行是key值，所以从第一行开始写入value值
        worksheet.write(row_num,0,cookies[row_num-1]['domain'])
        worksheet.write(row_num,1,cookies[row_num-1]['httpOnly'])
        worksheet.write(row_num,2,cookies[row_num-1]['name'])
        worksheet.write(row_num,3,cookies[row_num-1]['path'])
        worksheet.write(row_num,4,cookies[row_num-1]['secure'])
        worksheet.write(row_num,5,cookies[row_num-1]['value'])

    workbook.save('cnblog_Cookie.xls') #保存cookie文件

def login_cn():
    # (2)从excel读取cookie并添加
    workbook = xlrd.open_workbook('cnblog_Cookie.xls')
    worksheet = workbook.sheet_by_name('Sheet1')
    # 使用for循环读取cookie信息，并存放到cookieList表中。
    cookie_list = []
    for row_num in range(1, worksheet.nrows):
        cookie_dict = {}
        cookie_dict["domain"] = worksheet.cell_value(row_num, 0)
        cookie_dict["httpOnly"] = bool(worksheet.cell_value(row_num, 1))  # excel中的是true false是String类型，这里需要转换成bool类型
        cookie_dict["name"] = worksheet.cell_value(row_num, 2)
        cookie_dict["path"] = worksheet.cell_value(row_num, 3)
        cookie_dict["secure"] = True if worksheet.cell_value(row_num,
                                                             4) == 'TRUE' else False  # 也可以使用三目运算符把String类型转换成布尔类型
        cookie_dict["value"] = worksheet.cell_value(row_num, 5)
        cookie_list.append(cookie_dict)
    # 添加cookie
    for cookie in cookie_list:
        driver.add_cookie(cookie)
    # 添加后刷新浏览器自动登录
    time.sleep(3)
    driver.refresh()



file_dir = r"C:\Users\shx15\Desktop\文档\工作笔记"
file_name_list = os.listdir(file_dir)
file_file_list = [i for i in file_name_list if os.path.isfile(os.path.join(file_dir,i))]

def gain_context():
    article_name_list = file_file_list[37:]
    for file_name in article_name_list:
        blog_name = f"✍{file_name.split('.md')[0]}"
        file_path = os.path.join(file_dir, file_name)
        with open(file_path,"rt",encoding="utf8") as f:
            blog_res = f.read()
        print(f"============={blog_name}===========================================================")
        print(blog_res)
        print("===========================================================================")

        driver.find_element_by_xpath('/html/body/cnb-root/cnb-layout/div[2]/div[3]/div[1]/cnb-sidebar[1]/div/ul/li[1]/a').click()
        time.sleep(3)
        driver.find_element_by_xpath('//*[@id="post-title"]').send_keys(blog_name)
        driver.find_element_by_xpath('//*[@id="md-editor"]').send_keys(blog_res)
        time.sleep(1)
        driver.find_element_by_xpath('/html/body/cnb-root/cnb-layout/div[2]/div[3]/div[2]/div/cnb-spinner/div/cnb-post-editing-v2/cnb-post-editor/div[2]/div[2]/div[2]/span/cnb-post-body-images-extractor/div/cnb-spinner/div/button').click()
        time.sleep(5)
        driver.find_element_by_xpath('//*[@id="tags"]/ng-select/div/div/div[2]/input').send_keys("工作相关")
        time.sleep(0.5)
        driver.find_element_by_xpath('//*[@id="pwd"]').click()
        driver.find_element_by_xpath('//*[@id="tags"]/ng-select/div/div/div[3]/input').send_keys("linux系统")
        time.sleep(0.5)
        driver.find_element_by_xpath('//*[@id="pwd"]').click()
        time.sleep(0.5)
        driver.find_element_by_xpath('//*[@id="tags"]/ng-select/div/div/div[4]/input').send_keys("django相关")
        time.sleep(0.5)
        driver.find_element_by_xpath('//*[@id="pwd"]').click()
        time.sleep(0.5)
        driver.find_element_by_xpath('/html/body/cnb-root/cnb-layout/div[2]/div[3]/div[2]/div/cnb-spinner/div/cnb-post-editing-v2/cnb-post-editor/div[3]/cnb-spinner/div/cnb-submit-buttons/button[1]').click()
        time.sleep(360)


gain_context()
